package com.atguigu.mock.entity;

import com.atguigu.common.base.entity.AutoIdBase;
import com.atguigu.common.comment.Comment;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import java.math.BigDecimal;
import java.time.LocalDateTime;

@Entity
@Getter
@Setter
@NoArgsConstructor
@Comment("订单表")
public class OrderInfo extends AutoIdBase {
    @Comment("下单用户")
    @ManyToOne(optional = false)
    private Customer customer;

    @Comment("下单店铺")
    @ManyToOne(optional = false)
    private Shop shop;

    @Comment("订单状态 1.已下单 2.已支付 3.已出货 4.已评价 5.发起退单 6.已退款")
    private Integer status = 1;

    @Comment("原价")
    private BigDecimal originalAmount;

    @Comment("实际价格")
    private BigDecimal actualAmount;

    @Comment("优惠金额")
    private BigDecimal reduceAmount;

    @Comment("评分 1-5")
    private Integer rating;

    @Comment("评价")
    private String comment;

    @Comment("关联优惠记录")
    @ManyToOne
    private Promotion promotion;

    public OrderInfo(LocalDateTime createTime, Customer customer, Shop shop) {
        super(createTime);
        this.customer = customer;
        this.shop = shop;
        this.originalAmount = new BigDecimal(0);
        this.reduceAmount = new BigDecimal(0);
        this.actualAmount = new BigDecimal(0);
    }

    public boolean acceptDetail(OrderDetail orderDetail) {
        if (orderDetail == null) {
            return false;
        }
        setUpdateTime(orderDetail.getUpdateTime());
        this.originalAmount = this.originalAmount.add(orderDetail.getAmount());
        this.actualAmount = this.originalAmount.subtract(this.reduceAmount);
        return true;
    }

    public boolean acceptPromotion(Promotion promotion) {
        if (promotion == null || promotion.getThresholdAmount().compareTo(this.actualAmount) > 0) {
            return false;
        }
        this.promotion = promotion;
        this.reduceAmount = promotion.getReduceAmount();
        this.actualAmount = this.originalAmount.subtract(this.reduceAmount);
        return true;
    }

    public Payment generatePayment(LocalDateTime paymentCreateTime, LocalDateTime time) {
        Payment payment = new Payment(paymentCreateTime, this);
        payment.setUpdateTime(time);
        if (status == null || status != 1) {
            this.status = 1;
        }
        return payment;
    }

}
